<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="是否开启邀新奖励" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-decorator="['enabled', { initialValue: 1, rules: [{ required: true }] }]">
            <a-radio :value="1">开启</a-radio>
            <a-radio :value="0">关闭</a-radio>
          </a-radio-group>
          <div class="form-item-help">
            <small>如设置关闭则用户邀请新人，双方没有任何奖励</small>
          </div>
        </a-form-item>
        <div v-show="form.getFieldValue('enabled') == 1">
          <a-divider orientation="left">老用户奖励</a-divider>
          <a-form-item label="奖励类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-radio-group v-decorator="['initiator_award_type', { initialValue: 10, rules: [{ required: true }] }]"
              @change="onForceUpdate()">
              <a-radio :value="10">积分</a-radio>
              <a-radio :value="20">优惠券</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="奖励积分数量" :labelCol="labelCol" :wrapperCol="wrapperCol"
            v-show="form.getFieldValue('initiator_award_type') == 10">
            <a-input type="number" placeholder="请输入奖励积分"
              v-decorator="['initiator_points', { rules: [{ required: form.getFieldValue('initiator_award_type') == 10, message: '请输入至少1个字符' }] }]" />
          </a-form-item>
          <a-form-item label="奖励优惠券" :labelCol="labelCol" :wrapperCol="wrapperCol"
            v-show="form.getFieldValue('initiator_award_type') == 20">
            <SelectCoupon :defaultList="initiatorList"
              v-decorator="['initiator_coupon_id', { rules: [{ required: form.getFieldValue('initiator_award_type') == 20, message: '请选择适用的优惠券' }] }]" />
          </a-form-item>

          <a-divider orientation="left">新用户奖励</a-divider>
          <a-form-item label="奖励类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-radio-group v-decorator="['invitee_award_type', { initialValue: 10, rules: [{ required: true }] }]"
              @change="onForceUpdate()">
              <a-radio :value="10">积分</a-radio>
              <a-radio :value="20">优惠券</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="奖励积分数量" :labelCol="labelCol" :wrapperCol="wrapperCol"
            v-show="form.getFieldValue('invitee_award_type') == 10">
            <a-input type="number" placeholder="请输入奖励积分"
              v-decorator="['invitee_points', { rules: [{ required: form.getFieldValue('invitee_award_type') == 10, message: '请输入至少1个字符' }] }]" />
          </a-form-item>
          <a-form-item label="奖励优惠券" :labelCol="labelCol" :wrapperCol="wrapperCol"
            v-show="form.getFieldValue('invitee_award_type') == 20">
            <SelectCoupon :defaultList="inviteeList"
              v-decorator="['invitee_coupon_id', { rules: [{ required: form.getFieldValue('invitee_award_type') == 20, message: '请选择适用的优惠券' }] }]" />
          </a-form-item>
        </div>
        <a-form-item :wrapperCol="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { get } from 'lodash'
import * as Api from '@/api/setting/store'
import * as CouponApi from '@/api/market/coupon'
import { SelectCoupon } from '@/components'

export default {
  components: {
    SelectCoupon
  },
  data() {
    return {
      // 标签布局属性
      labelCol: { span: 4 },
      // 输入框布局属性
      wrapperCol: { span: 10 },
      // loading状态
      isLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录详情
      record: {},
      // 当前设置项的key
      key: 'inviter_activity',
      // 老用户优惠券列表
      initiatorList: [],
      // 新用户优惠券列表
      inviteeList: [],
    }
  },
  // 初始化数据
  created() {
    // 获取当前详情记录
    this.getDetail()
  },
  methods: {

    // 获取当前详情记录
    getDetail() {
      this.isLoading = true
      Api.detail(this.key)
        .then(result => {
          // 当前记录
          this.record = result.data.values
          // 设置默认值
          this.setFieldsValue()

          // 获取适用范围：指定的优惠券
          this.getContainCouponList()
        })
        .finally(() => this.isLoading = false)
    },

    // 设置默认值
    setFieldsValue() {
      const { record, form: { setFieldsValue } } = this
      // 表单内容
      this.$nextTick(() => {
        setFieldsValue(pick(record, ['enabled', 'initiator_award_type', 'initiator_points', 'initiator_coupon_id', 'invitee_award_type', 'invitee_points', 'invitee_coupon_id']))
      })
    },

    // 获取指定的商品列表
    getContainCouponList() {
      let initiatorIds = this.record.initiator_coupon_id //老用户
      let inviteeIds = this.record.invitee_coupon_id //新用户

      this.isLoading = true
      CouponApi.list()
        .then(result => {
          // 老用户
          if (initiatorIds) {
            this.initiatorList = result.data.list.data.filter(item => item.coupon_id === initiatorIds);
          }
          // 新用户
          if (inviteeIds) {
            this.inviteeList = result.data.list.data.filter(item => item.coupon_id === inviteeIds);
          }
        })
        .finally(() => this.isLoading = false)
    },

    // 手动强制更新页面
    onForceUpdate(bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    // 提交到后端api
    onFormSubmit(values) {
      this.isLoading = true

      // 老用户
      if (values.initiator_award_type == 10) {
        values.initiator_coupon_id = ""
      } else if (values.initiator_award_type == 20) {
        values.initiator_points = ""
      }
      // 新用户
      if (values.invitee_award_type == 10) {
        values.invitee_coupon_id = ""
      } else if (values.invitee_award_type == 20) {
        values.invitee_points = ""
      }
      Api.update(this.key, { form: values })
        .then(result => this.$message.success(result.message, 1.5))
        .finally(() => this.isLoading = false)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-form-item-control {
  padding-left: 10px;

  .ant-form-item-control {
    padding-left: 0;
  }
}
</style>
